import { ref } from 'vue'
import { defineStore } from 'pinia'
import { login as loginApi, getUserInfo as getUserInfoApi, logout as logoutApi, type LoginRequest, type UserInfo } from '@/api/auth'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>(localStorage.getItem('token') || '')
  const userInfo = ref<UserInfo | null>(null)

  // 登录
  async function login(loginData: LoginRequest) {
    try {
      const response = await loginApi(loginData)
      token.value = response.token
      userInfo.value = response.user
      
      // 保存token到localStorage
      localStorage.setItem('token', response.token)
      
      return response
    } catch (error) {
      throw error
    }
  }

  // 获取用户信息
  async function getUserInfo() {
    try {
      const info = await getUserInfoApi()
      userInfo.value = info
      return info
    } catch (error) {
      throw error
    }
  }

  // 登出
  async function logout() {
    try {
      await logoutApi()
    } catch (error) {
      // 即使API调用失败，也要清除本地状态
      console.error('Logout API failed:', error)
    } finally {
      // 清除状态
      token.value = ''
      userInfo.value = null
      localStorage.removeItem('token')
    }
  }

  // 检查是否有权限
  function hasPermission(permissionCode: string): boolean {
    if (!userInfo.value?.permissions) return false
    return userInfo.value.permissions.some(permission => permission.code === permissionCode)
  }

  // 检查是否有角色
  function hasRole(roleName: string): boolean {
    if (!userInfo.value?.roles) return false
    return userInfo.value.roles.some(role => role.name === roleName)
  }

  return {
    token,
    userInfo,
    login,
    getUserInfo,
    logout,
    hasPermission,
    hasRole
  }
})
